<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="format-detection" content="telephone=no,email=no" />
		<title>购物车子页面</title>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link href="css/style.css" rel="stylesheet" />
	</head>
	<body>
		<div id="pullrefresh" class="mui-content mui-scroll-wrapper transparent">
			<div class="mui-scroll">
				<ul class="cart-list" id="cartList"></ul>
			</div>	
		</div>
		<div class="cart-bottom transparent">
			<div class="mui-checkbox mui-left">
				<label>全选</label>
				<input name="s-checkAll" id="s-checkAll" type="checkbox">
			</div>
			<div class="cart-total-price">
				<p>合计：<span id="s-total-money">¥ 0</span></p>
				<h5>不含邮费</h5>
			</div>
			<a class="submit-cart" id="submitCart">结算<span id="s-total-num"></span></a>
		</div>
		
		<script src="js/zepto.min.js"></script>
		<script src="js/mui.min.js"></script>
		<script src="js/delayimg.min.js"></script>
		<script src="js/app.js"></script>
		<script>
			var loadPage;
			mui.init({
				pullRefresh : {
				    container:'#pullrefresh',
				    deceleration:0.0006,
				    down : {
						contentdown : "下拉可以刷新",
						contentover : "释放立即刷新",
						contentrefresh : "正在刷新...",
						callback :function(){
							setTimeout(function(){
								loadPage();
								document.getElementById('s-checkAll').checked=false;
								document.getElementById('s-total-money').innerHTML='0.00';
								document.getElementById('s-total-num').innerHTML='';
								mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
							},300)
						}
				    }
				}
			});
			
			mui.plusReady(function() {
				var w=plus.nativeUI.showWaiting('',{padlock:true});
				plus.webview.currentWebview().setStyle({scrollIndicator:'none'});
				
				loadPage=function(){
					mui.ajax(URL+'api/Cart/GetCartProduct',{
						dataType:'json',
						type:'get',
						timeout:10000,
						success:function(data){
							if(data.Success=='true'){
								var list='';
						        if (data.Shop.length > 0) {
						        	for(var i=0;i<data.Shop.length;i++){
										var shopPrice=0,
											str = '',
											strDisabled='';
										for(var j=0;j<data.Shop[i].length;j++){
						                    if (data.Shop[i][j].Status == 1) {
												str += '\
												<div class="mui-checkbox mui-left cart-list-goods" data-skuid="'+data.Shop[i][j].SkuId+'" data-cartid="'+data.Shop[i][j].CartItemId+'">\
													<div class="cart-goods">\
														<a class="goods-url goods-img" data-url = "'+data.Shop[i][j].Id+'"><img src="images/blank.gif" data-delay="'+data.Shop[i][j].ImgUrl+'"/></a>\
														<div class="cart-goods-detail">\
															<p><span>¥<em>'+data.Shop[i][j].Price+'</em></span><a class="goods-url" data-url="'+data.Shop[i][j].Id+'">'+data.Shop[i][j].Name+'</a></p><h5>';
															if(data.Shop[i][j].Size!='')
																str += '尺寸：'+data.Shop[i][j].Size+'&nbsp;&nbsp;';
															if(data.Shop[i][j].Color!='')
																str += '颜色：'+data.Shop[i][j].Color+'&nbsp;&nbsp;';
															if(data.Shop[i][j].Version!='')
																str += '规格：'+data.Shop[i][j].Version;
															str += '</h5><div class="mui-numbox" data-numbox-min="1" data-numbox-max="100">\
																<button class="mui-btn mui-numbox-btn-minus" type="button">-</button>\
																<input class="mui-numbox-input" type="number" value="'+data.Shop[i][j].Count+'" />\
																<button class="mui-btn mui-numbox-btn-plus" type="button">+</button>\
															</div>\
														</div>\
													</div>\
													<input name="checkItem" type="checkbox">\
													<em class="mui-icon mui-icon-trash"></em>\
												</div>';
						                    }else{
						                    	strDisabled += '\
												<div class="mui-checkbox mui-left cart-list-goods mui-disabled" data-skuid="'+data.Shop[i][j].SkuId+'">\
													<div class="cart-goods">\
														<a class="goods-url goods-img"><img style="opacity:0.5!important" src="images/blank.gif" data-delay="'+data.Shop[i][j].ImgUrl+'"/></a>\
														<div class="cart-goods-detail">\
															<p><span>¥<em>'+data.Shop[i][j].Price+'</em></span><a class="goods-url">'+data.Shop[i][j].Name+'</a></p><h5>已失效</h5>\
															<div class="mui-numbox" data-numbox-min="0" data-numbox-max="0">\
																<button class="mui-btn mui-numbox-btn-minus" type="button" disabled >-</button>\
																<input class="mui-numbox-input" type="number" value="0" disabled />\
																<button class="mui-btn mui-numbox-btn-plus" type="button" disabled >+</button>\
															</div>\
														</div>\
													</div>\
													<input name="checkItemDisabled" type="checkbox" disabled>\
													<em class="mui-icon mui-icon-trash"></em>\
												</div>';
						                    }
						                }
										
										list+='<li class="mui-input-group">\
											<div class="mui-checkbox mui-left cart-list-shop">\
											<div class="cart-shop"><span class="cart-shop-price"></span><a class="vshop-url" data-url = "'+data.Shop[i][0].VShopId+'">'+data.Shop[i][0].ShopName+'</a></div>\
											<input name="checkShop" type="checkbox">\
											</div>'+str+strDisabled+'</li>';
						            }
						        	document.getElementById('cartList').innerHTML=list;
						        	delayimg.init();
						            bindSelectAll();
						            mui('.mui-numbox').numbox();
						        }else{
						        	var html='<div class="empty-show"><h4>抱歉，购物车没有任何宝贝！</h4><button id="closeWv" class="mui-btn mui-btn-negative">马上去商城寻宝</button></div>';
						        	document.getElementsByClassName('mui-content')[0].innerHTML=html;
						        }
						        w.close();
								document.getElementsByClassName("mui-content")[0].className="mui-content mui-scroll-wrapper";
								document.getElementsByClassName("cart-bottom")[0].className="cart-bottom";
							}
						},
						error:function(xhr,type,errorThrown){
							w.close();
							reloadWvLoad();
						}
					});
				}
				
				loadPage();
				
				//添加列表项的点击事件
				mui('#cartList').on('tap', '.goods-url', function() {
					var id = this.getAttribute('data-url');
					showProduct(id);
				});
				
				mui('#cartList').on('tap', '.vshop-url', function() {
					var vshopid = this.getAttribute('data-url');
					if(vshopid==0){
						plus.nativeUI.toast('该店铺暂未开通微店')
					}else{
						showVshop(vshopid,'/')
					}
				});
				
				document.getElementById('submitCart').addEventListener('tap',function(){
					setTimeout(function(){
						var checkPro=$('#cartList input[name="checkItem"]:checked');
						if(checkPro.length>0){
							var skuArr=[],
								cartidArr=[],
								ArrSkuId,
								ArrCount,
								data;
							$('#cartList input[name="checkItem"]:checked').each(function(){
								ArrSkuId=$(this).parent().data('skuid');
								ArrCount=$(this).parent().find('input[type="number"]').val();
								skuArr.push({skuId:ArrSkuId,count:ArrCount});
								cartidArr.push($(this).parent().data('cartid'));
							});
							data=JSON.stringify({skus:skuArr});
							
							mui.ajax(URL+'api/Cart/PostUpdateCartItem',{
								data:data,
								dataType:'json',
								contentType:'application/json',
								type:'POST',
								timeout:10000,
								success:function(data){
									if(data.Success=="true"){
										mui.openWindow({
											id:'order-submit.html',
											url:'order-submit.html',
											extras:{
												cartItemId:cartidArr.join(',')
										    },
											show: {
												autoShow:true,
												aniShow: 'pop-in'
											},
											waiting: {
												autoShow: false
											}
										});
									}else{
										plus.nativeUI.toast('结算失败，请稍候重试');
									}
								},
								error:function(xhr,type,errorThrown){
									plus.nativeUI.toast('结算失败，请检查网络')
								}
							});
						}else{
							plus.nativeUI.toast('请至少选择一件宝贝')
						}
					},100)
				});
				
			});
			
			document.addEventListener('updateData', function() {
				loadPage();
				document.getElementById('s-checkAll').checked=false;
				document.getElementById('s-total-money').innerHTML='0.00';
				document.getElementById('s-total-num').innerHTML='';
			});
			
			mui('#cartList').on('tap','.mui-icon-trash',function(){
		    	var _this = $(this),
		    		btnArray = ['取消', '确认'];
				mui.confirm('确认删除该条宝贝？', '', btnArray, function(e) {
					if (e.index == 1) {
						var skuId=_this.parent().data('skuid'),
				    		state = app.getState(),
				    		data=JSON.stringify({skuIds:skuId,userId:state.userId});
				    	mui.ajax(URL+'api/Cart/PostDeleteCartProduct',{
							data:data,
							dataType:'json',
							type:'POST',
							contentType:'application/json',
							timeout:10000,
							success:function(data){
								if(data.Success=="true"){
									var parentN=_this.parents('li');
									if(parentN.find('.cart-list-goods').length<=1)
										parentN.remove();
									else
										_this.parent().remove();
									plus.nativeUI.toast('删除宝贝成功')
								}else{
									plus.nativeUI.toast('删除失败，请稍后重试')
								}
							},
							error:function(xhr,type,errorThrown){
								plus.nativeUI.toast('请求失败，请检查网络')
							}
						});
					}
				});
		    	
		    });
			
			function bindSelectAll() {
			    $('input[name="s-checkAll"]').change(function () {
			        var checked = this.checked;
					$('#cartList input[type=checkbox]').not(':disabled').prop('checked',checked);
			        if (checked) {
			    		$('#cartList li').each(function () {
			    			var t = 0,
								c=0;
			    			$(this).find('.cart-list-goods').not('.mui-disabled').each(function(){
			    				var a = $(this).find('em').html();
								var c = $(this).find('input[type="number"]').val();
								t += (+a)*c;
			    			});
			    			
							$(this).find('.cart-shop-price').html('¥'+t.toFixed(2));
						})
						$('#s-total-money').html(getCheckProductPrice());
			        	$('#s-total-num').html(getCheckProductCount());
						
			        }
			        else {
			            $('#s-total-money').html("0.00");
						$('#cartList .cart-shop-price,#s-total-num').html('');
						
			
			        }
			    });
			
			    $('input[name="checkShop"]').change(function () {
			        var checked = this.checked;
					$(this).parent().siblings().find('input[name="checkItem"]').prop('checked',checked);
					
			        var allShopChecked = true;
			        $('#cartList input[type="checkbox"]').each(function () {
			            if (!this.checked) {
			                allShopChecked = false;
			            }
			        });
			        if (allShopChecked)
			            $('input[name="s-checkAll"]').prop('checked', true);
			        else
			            $('input[name="s-checkAll"]').prop('checked',false);
					
					var t = 0,
						c=0;
					$.each($(this).parent().siblings(), function () {
						if($(this).find('input[name="checkItem"]:checked').length>0){
							var a = $(this).find('input[name="checkItem"]:checked').siblings('div').find('em').html();
							c = $(this).find('input[name="checkItem"]:checked').siblings('div').find('input[type="number"]').val();
							t += (+a)*c;
						}
					})
					if(t!=0)
						$(this).siblings().find('.cart-shop-price').html('¥'+t.toFixed(2));
					else
						$(this).siblings().find('.cart-shop-price').html('');
					
					$('#s-total-money').html(getCheckProductPrice());
			        $('#s-total-num').html(getCheckProductCount());
			    });
			
			    $('input[name="checkItem"]').change(function () {
					var checked = this.checked;

			        //判断店铺下的所有商品是否全选中
			        var allProductChecked = true;
					$(this).parent().siblings('.cart-list-goods').not('.mui-disabled').each(function() {
						if (!$(this).find('input[name="checkItem"]').prop('checked'))
			                allProductChecked = false;
					});
			        if (allProductChecked)
			            $(this).parent().siblings().find('input[name="checkShop"]').prop('checked', checked);
			        else
						$(this).parent().siblings().find('input[name="checkShop"]').removeAttr('checked');;
			
			        //判断所有店铺是否都选中了
			        var allShopChecked = true;
			        $('#cartList input[name="checkItem"]').each(function () {
			            if (!this.checked) {
			                allShopChecked = false;
			            }
			        });
			        if (allShopChecked)
			            $('input[name="s-checkAll"]').prop('checked', true);
			        else
			            $('input[name="s-checkAll"]').removeAttr('checked');
			
					getChangeShopPrice($(this));
			        
			    });
			    
			    $('#cartList input[type="number"]').change(function () {
			    	if($(this).parents('.cart-goods').siblings('input').is(':checked')){
			    		var that=$(this);
			    		setTimeout(function(){
			    			getChangeShopPrice(that);
			    		},100)
				    }
			    });
			
			}
			
			function getChangeShopPrice(_this){
				var t = 0,
					c=0;
	    		_this.parents('li').find('input[name="checkItem"]:checked').each(function () {
					var a = $(this).siblings().find('em').html();
					var c = $(this).siblings().find('input[type="number"]').val();
					t += (+a)*c;
				})
				if(t!=0)
					_this.parents('li').find('.cart-shop-price').html('¥'+t.toFixed(2));
				else
					_this.parents('li').find('.cart-shop-price').html('');
				$('#s-total-money').html(getCheckProductPrice());
	        	$('#s-total-num').html(getCheckProductCount());
			}
			
			
			function getCheckProductPrice() {
			    var t = 0;
			    $.each($('input[name="checkItem"]:checked'), function () {
			        var a = $(this).siblings().find('em').html();
			        var c = $(this).siblings().find('input[type="number"]').val();
			        t += (+a)*c;
			    });
			    t='¥ '+t.toFixed(2);
			    return t;
			}
			
			function getCheckProductCount() {
			    var t = 0;
			    $.each($('input[name="checkItem"]:checked'), function () {
			        var c = $(this).siblings().find('input[type="number"]').val();
			        d = parseInt(c);
			        t += d;
			    });
			    t='('+t+')';
			    return t;
			}

			
		</script>
	</body>

</html>